package com.zyc.studentstudy.utils

import timber.log.Timber
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader

/**
 * Created by zhangyuncai on 2025/6/13.
 * 描述：
 */
object ProcessKT {
    /**
     * 执行对应的cmd 命令 注意:此方法耗时，需要异步处理
     * @param cmd
     * @return 返回结果
     */
    fun execSuCmdResult(cmd: String): String {
        var process: Process? = null
        var os: DataOutputStream? = null
        var reader: BufferedReader? = null
        var errorReader: BufferedReader? = null
        var outputCmd = ""
        try {
            // 执行su命令获取root权限
            process = Runtime.getRuntime().exec("su")
            os = DataOutputStream(process.outputStream)
            // 发送shell命令
            os.writeBytes("$cmd\n")
            os.writeBytes("exit\n")
            os.flush()
            // 获取命令执行结果
            reader = BufferedReader(InputStreamReader(process.inputStream))
            errorReader = BufferedReader(InputStreamReader(process.errorStream))
            // 读取标准输出
            var line: String?
            val output = java.lang.StringBuilder()
            while ((reader.readLine().also { line = it }) != null) {
                output.append(line).append("\n")
            }
            Timber.d("命令输出：$output")
            outputCmd = output.toString()

            // 读取错误输出
            val error = java.lang.StringBuilder()
            while ((errorReader.readLine().also { line = it }) != null) {
                error.append(line).append("\n")
            }
            if (error.isNotEmpty()) {
                Timber.d("命令错误：$error")
                outputCmd = error.toString()
            }
            // 等待命令执行完成并获取返回值
            val exitCode = process.waitFor()
            Timber.d("命令退出码：$exitCode")
        } catch (e: IOException) {
            Timber.d("%s%s", "IO异常: ", e.message)
        } catch (e: InterruptedException) {
            Timber.d("%s%s", "线程中断异常: ", e.message)
            Thread.currentThread().interrupt()
        } finally {
            // 关闭资源
            try {
                os?.close()
                reader?.close()
                errorReader?.close()
                process?.destroy()
            } catch (e: IOException) {
                Timber.d("%s%s", "关闭资源异常: ", e.message)
            }
        }
        return outputCmd
    }

}